package wifiunion.com.notice.fragment;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.NoticeTargetAdapter;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.entity.NoticeTopGroupEntity;
import wifiunion.com.notice.entity.SubNoticeTargetEntity;
import wifiunion.com.notice.presenter.GetNoticeDetailPresenter;
import wifiunion.com.notice.presenter.GetNoticeFromPresenter;
import wifiunion.com.notice.presenter.GetNoticeTargetListPresenter;
import wifiunion.com.notice.presenter.GetNoticeTopGroupListPresenter;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.AddNoticeTargetDeviceDialog;
import wifiunion.com.notice.widget.selectmemberdialog.SelectMemberDialog;

/**
 * Created by Administrator on 2016/11/28.
 * 添加通知对象
 */

public class AddNoticeTargetFragment extends BaseFragment implements NoticeContact.View, ExpandableListView.OnGroupClickListener, ExpandableListView.OnGroupExpandListener, View.OnClickListener {

    private View mMainView;
    private int pageType;
    private String noticeUuid;
    private ExpandableListView elist;
    private NoticeTargetAdapter mNoticeTargetAdapter;
    private String mAuthtoken;
    private ArrayList<NoticeTopGroupEntity> gpList = new ArrayList<NoticeTopGroupEntity>();

    private GetNoticeTopGroupListPresenter mGetNoticeTopGroupListPresenter;

    private GetNoticeTargetListPresenter mGetNoticeTargetListPresenter;

    private GetNoticeFromPresenter mGetNoticeFromPresenter;

    //当前操作的currentNoticeTopGroupEntity;
    private NoticeTopGroupEntity currentNoticeTopGroupEntity;

    private AddNoticeTargetDeviceDialog mAddNoticeTargetDeviceDialog;
//    private AddNoticeTargetUserDialog mAddNoticeTargetUserDialog;

    private TextView headDowntv;
    private TextView headUpTv;

    private ImageView ovaltzdxIv;
    private TextView titletzdxTv;
    private ImageView switchIv;

    private int isNotification;//0 不通知  1通知
    private NoticeInfoList mNoticeInfoList;

    private GetNoticeDetailPresenter mGetNoticeDetailPresenter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addnoticetarget, container, false);
        mGetNoticeTopGroupListPresenter = new GetNoticeTopGroupListPresenter(getContext(), this);
        mGetNoticeTargetListPresenter = new GetNoticeTargetListPresenter(getContext(), this);
        mGetNoticeFromPresenter = new GetNoticeFromPresenter(getContext(), this);
        mGetNoticeDetailPresenter = new GetNoticeDetailPresenter(getContext(), this);
        Bundle bundle = getArguments();
        if (null != bundle) {
            pageType = bundle.getInt("pageType");
            if (pageType == 0) {
                noticeUuid = bundle.getString("noticeUuid");
            } else if (pageType == 1 || pageType == 2) {
                mNoticeInfoList = (NoticeInfoList) bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();
            }

        }
        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, getActivity());
        initview();
        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

//        initData();

        gpList.clear();
        getTopGroupList();

    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
//                    getFragmentManager().popBackStack();
                    getActivity().getSupportFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }


    @Override
    public void initview() {

        switchIv = (ImageView) mMainView.findViewById(R.id.iv_notice_switch);
        switchIv.setOnClickListener(this);

        if (pageType == 0) {
            getNoticeDetails(noticeUuid);

        } else if (pageType == 1) {
            switchIv.setEnabled(false);
            if (mNoticeInfoList.getIsNotificationFrom() == 0) {
                switchIv.setBackgroundResource(R.drawable.off);
            } else {
                switchIv.setBackgroundResource(R.drawable.on);
            }
        } else if (pageType == 2) {
            switchIv.setEnabled(true);
            getNoticeDetails(noticeUuid);

//            if(mNoticeInfoList.getIsNotificationFrom() ==0)
//            {
//                switchIv.setBackgroundResource(R.drawable.off);
//                isNotification = 0;
//            }
//            else
//            {
//                switchIv.setBackgroundResource(R.drawable.on);
//                isNotification = 1;
//            }
        }

        ovaltzdxIv = (ImageView) mMainView.findViewById(R.id.oval_tzdx_iv);
        ovaltzdxIv.setBackgroundResource(R.drawable.notice_mark_material_select);
        titletzdxTv = (TextView) mMainView.findViewById(R.id.title_tzdx_tv);


        headDowntv = (TextView) mMainView.findViewById(R.id.notice_head_down_tv);
        headDowntv.setOnClickListener(this);
        headUpTv = (TextView) mMainView.findViewById(R.id.notice_head_up_tv);
        headUpTv.setOnClickListener(this);

        elist = (ExpandableListView) mMainView.findViewById(R.id.elist);
        elist.setGroupIndicator(null);
        mNoticeTargetAdapter = new NoticeTargetAdapter(getActivity(), gpList, itemclick);
        elist.setAdapter(mNoticeTargetAdapter);
        elist.setOnGroupClickListener(this);
//        只打开一个分组
        elist.setOnGroupExpandListener(this);

    }

    public void getNoticeDetails(String noticeUuid) {

        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);

        mGetNoticeDetailPresenter.getNoticeDetail(params);

    }


    @Override
    public void initData() {


    }

    public void getTopGroupList() {
        HashMap<String, Object> mParams = new HashMap<>();

        mParams.put("Authorization", mAuthtoken);

        mGetNoticeTopGroupListPresenter.getTopGroupList(mParams);
    }


    private View.OnClickListener itemclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int i = v.getId();
            if (i == R.id.child_optitem_name) {//添加或者编辑模式可用
                if (pageType == 0 || pageType == 2) {
                    int parenttag = (int) v.getTag();
                    currentNoticeTopGroupEntity = gpList.get(parenttag);
                    if ("1".equals(currentNoticeTopGroupEntity.getGroupUuid())) {
                        //添加通知对象管理
//                        mAddNoticeTargetUserDialog = new AddNoticeTargetUserDialog(getContext(), getActivity(), noticeUuid, currentNoticeTopGroupEntity.getGroupUuid(), myListener);
//                        mAddNoticeTargetUserDialog.setTitleMsg("添加通知对象");
//                        mAddNoticeTargetUserDialog.show();
                        SelectMemberDialog selectMemberDialog = SelectMemberDialog.newInstance(noticeUuid, -2, 3, currentNoticeTopGroupEntity.getGroupUuid());
                        selectMemberDialog.setCallback(myListener);
                        selectMemberDialog.show(getFragmentManager(), "");

                    } else if ("2".equals(currentNoticeTopGroupEntity.getGroupUuid())) {
                        //添加通知对象用户
//                        mAddNoticeTargetUserDialog = new AddNoticeTargetUserDialog(getContext(), getActivity(), noticeUuid, currentNoticeTopGroupEntity.getGroupUuid(), myListener);
//                        mAddNoticeTargetUserDialog.setTitleMsg("添加通知对象");
//                        mAddNoticeTargetUserDialog.show();

                        SelectMemberDialog selectMemberDialog = SelectMemberDialog.newInstance(noticeUuid, -2, 3, currentNoticeTopGroupEntity.getGroupUuid());
                        selectMemberDialog.setCallback(myListener);
                        selectMemberDialog.show(getFragmentManager(), "");


                    } else {
                        //添加通知对象闸机
                        mAddNoticeTargetDeviceDialog = new AddNoticeTargetDeviceDialog(getContext(), getActivity(), noticeUuid, currentNoticeTopGroupEntity.getGroupUuid(), myListener);
                        mAddNoticeTargetDeviceDialog.setTitleMsg("添加通知对象");
                        mAddNoticeTargetDeviceDialog.show();

                    }
                }


            }

        }
    };

    @Override
    public void onProgress() {

    }

    @Override
    public void onError(Object obj) {

    }

    @Override
    public void onSuccess(Object obj) {

    }

    @Override
    public void getGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeListSuccess(Object obj) {


    }

    @Override
    public void getNotificationUserSuccess(Object obj) {

    }

    //获取顶层分组成功
    @Override
    public void getNotificationRelGroupList(final Object obj) {

        if (null != getActivity()) {
            ArrayList<NoticeTopGroupEntity> list = (ArrayList<NoticeTopGroupEntity>) obj;
            if (null != list) {
                gpList.addAll(list);
                mNoticeTargetAdapter.notifyDataSetChanged();
            }

        }


    }

    @Override
    public void getNoticeRelGroupMemberListSuccess(Object obj) {

    }

    @Override
    public void addNoticeSBDXSuccess(String noticeUuid) {

    }

    @Override
    public void addSBSDSuccess(Object obj) {

    }

    @Override
    public void onGetDeviceLocListSuccess(Object obj) {

    }

    @Override
    public void onGetDeviceListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeDeviceSuccess(Object obj) {

    }

    @Override
    public void getTopGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeTargetListSuccess(final Object obj) {
        ArrayList<SubNoticeTargetEntity> list = (ArrayList<SubNoticeTargetEntity>) obj;
        if (null != list) {
            currentNoticeTopGroupEntity.setSubNoticeTargetList(list);
            mNoticeTargetAdapter.notifyDataSetChanged();
        }
        elist.expandGroup(gpList.indexOf(currentNoticeTopGroupEntity));


    }

    @Override
    public void onGetNoticeTargetRelGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeTarGetDeviceSuccess(Object obj) {

    }

    @Override
    public void addNoticeDataSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeSuccess(Object obj) {

    }

    @Override
    public void addNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void addNoticeRelGroupSuccess(Object obj) {

    }

    @Override
    public void setNoticeFromSuccess(Object obj) {

        AddNoticeDataFragment atf = new AddNoticeDataFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("pageType", pageType);

        if (pageType == 0) {
            bundle.putString("noticeUuid", noticeUuid);
            atf.setArguments(bundle);
            //跳转到添加设备页面
            getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "46").addToBackStack(null).commit();
        } else if (pageType == 2) {
            bundle.putSerializable("notice", mNoticeInfoList);
            atf.setArguments(bundle);
            //跳转到添加设备页面
            getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "46").addToBackStack(null).commit();
        }

    }

    @Override
    public void getNoticeDetailSuccess(final Object obj) {


        if (null != getActivity()) {


            NoticeInfoList mNoticeInfoList = (NoticeInfoList) obj;
            if (null != mNoticeInfoList) {

                if (mNoticeInfoList.getIsNotificationFrom() == 0) {
                    switchIv.setBackgroundResource(R.drawable.off);
                    isNotification = 0;
                } else {
                    switchIv.setBackgroundResource(R.drawable.on);
                    isNotification = 1;
                }


            }

        }


    }

    @Override
    public void deleteNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }

    public void getChildDataByUuid(NoticeTopGroupEntity topGroup) {
        //加载子菜单
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        params.put("pageNum", String.valueOf(1));
        params.put("pageSize", String.valueOf(5000));
        params.put("uuid", noticeUuid);
        params.put("targetType", topGroup.getGroupUuid());

        mGetNoticeTargetListPresenter.getNoticeTargetList(params);

    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

        boolean expanded = parent.isGroupExpanded(groupPosition);
        currentNoticeTopGroupEntity = gpList.get(groupPosition);
        if (!expanded) {
            if (!currentNoticeTopGroupEntity.getSubNoticeTargetList().isEmpty()) {
                elist.expandGroup(groupPosition);
            } else {
                getChildDataByUuid(currentNoticeTopGroupEntity);

            }
            return true;
        }
        return false;
    }

    @Override
    public void onGroupExpand(int groupPosition) {

        for (int i = 0; i < mNoticeTargetAdapter.getGroupCount(); i++) {
            if (i != groupPosition
                    && elist.isGroupExpanded(groupPosition)) {
                elist.collapseGroup(i);
            } else {
                if (gpList.get(groupPosition).getSubNoticeTargetList().isEmpty()) {

                } else {
//                    if (mList.get(groupPosition).getIsSelected() == 1) {
//                        for (DeviceRlGroupDetail dgd : mList.get(groupPosition).getChilddata()) {
//                            dgd.setIsSelected(1);
//                        }
//                        mAdapter.notifyDataSetChanged();
//                    }
                }
            }
        }


    }

    private MyNoticeListener myListener = new MyNoticeListener() {
        @Override
        public void refreshData(final String text) {

            if ("1".equals(currentNoticeTopGroupEntity.getGroupUuid()) || "2".equals(currentNoticeTopGroupEntity.getGroupUuid())) {
//                if(null !=mAddNoticeTargetUserDialog)
//                {
//                    mAddNoticeTargetUserDialog.dismiss();
//                }
            } else {
                if (null != mAddNoticeTargetDeviceDialog) {
                    mAddNoticeTargetDeviceDialog.dismiss();
                }
            }

            currentNoticeTopGroupEntity.setSubNoticeTargetList(null);
            getChildDataByUuid(currentNoticeTopGroupEntity);

        }

        @Override
        public void refreshCancelData(final String text) {

        }

        @Override
        public void onResponse(List<Object> data) {

        }

    };


    @Override
    public void onClick(View view) {

        int i = view.getId();
        if (i == R.id.notice_head_up_tv) {
            getActivity().getSupportFragmentManager().popBackStack();


        } else if (i == R.id.notice_head_down_tv) {
            if (pageType == 0 || pageType == 2) {
//                    if(isNotification ==0)
//                    {
//                        boolean  result = false;
//                        for(NoticeTopGroupEntity nge  :gpList)
//                        {
//                            if(null != nge.getSubNoticeTargetList() && nge.getSubNoticeTargetList().size() > 0)
//                            {
//                                result = true;
//                                break;
//                            }
//
//                        }
//                        if(result)
//                        {
//                            HashMap<String, Object> params = new HashMap<>();
//                            params.put("Authorization", mAuthtoken);
//                            params.put("uuid",noticeUuid);
//                            params.put("isNotification", String.valueOf(isNotification));
//                            mGetNoticeFromPresenter.setisNotificationFrom(params);
//
//                        }
//                        else
//                        {
//                            Toast.makeText(getContext(),"请先选择通知对象",Toast.LENGTH_SHORT).show();
//
//
//                        }
//
//
//
//                    }
//                    else
//                    {

                HashMap<String, Object> params = new HashMap<>();
                params.put("Authorization", mAuthtoken);
                params.put("uuid", noticeUuid);
                params.put("isNotification", String.valueOf(isNotification));
                mGetNoticeFromPresenter.setisNotificationFrom(params);
//                    }


            } else if (pageType == 1) {

                AddNoticeDataFragment atf = new AddNoticeDataFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("notice", mNoticeInfoList);
                bundle.putInt("pageType", pageType);
                atf.setArguments(bundle);
                //跳转到添加设备页面
                getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "46").addToBackStack(null).commit();
            }
//                else if(pageType == 2)
//                {
//                    HashMap<String, Object> params = new HashMap<>();
//                    params.put("Authorization", mAuthtoken);
//                    params.put("uuid",noticeUuid);
//                    params.put("isNotification", String.valueOf(isNotification));
//                    mGetNoticeFromPresenter.setisNotificationFrom(params);
//                }


        } else if (i == R.id.iv_notice_switch) {
            if (isNotification == 0) {
                isNotification = 1;
                switchIv.setBackgroundResource(R.drawable.on);
            } else if (isNotification == 1) {
                isNotification = 0;
                switchIv.setBackgroundResource(R.drawable.off);
            }
        }
    }
}
